﻿using System;
using AspNetCoreRateLimit;
using Zhongjiu.Common;
//using log4net;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
namespace Zhongjiu.Extensions
{
  /// <summary>
  /// ip 限流
  /// </summary>
  public static class IpLimitMiddleware
  {
    //private static readonly ILog Log = LogManager.GetLogger(typeof(IpLimitMiddleware));
    private static ILogger _logger;
    public static void UseIpLimitMiddle(this IApplicationBuilder app, ILoggerFactory log)
    {
      if (app == null) throw new ArgumentNullException(nameof(app));
      _logger = log.CreateLogger(typeof(IpLimitMiddleware));
      try
      {
        if (Appsettings.app("Middleware", "IpRateLimit", "Enabled").ToBool())
        {
          app.UseIpRateLimiting();
        }
      }
      catch (Exception e)
      {
        _logger.LogError($"Error occured limiting ip rate.\n{e.Message}");
        throw;
      }
    }
  }
}
